// pages/award/index.js
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    id:'',
    award:{},
    index:0,
    starIndex:0,
    students:[],
    searchValue:'',
    canmaraShow:false,
    studentShow:false,
    imgList:[],
    modelList:[],
    list4Serach:[],
    remark:"",
    postAward:{}

  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.setData({
      id:options.id
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {
    this.get()
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  },
  get:function(){
    let that = this;
    app.api.getAward(this.data.id).then(res => {
      res.data.eduStarVos.forEach(item=>{
        for(const ent of res.data.eduTeacherStarVos){
          if(ent.starid == item.starid){
            item.qty = ent.qty
            break;
          }
        }
        });
      if(res.code == 200){
        that.setData({
          award : res.data,
          list4Serach:res.data.eduStudentVos
        })
      }
    })
  },
  changeStudent(event){
    this.setData({
      index:event.detail.value
    })
  },
  changeStar(event){
    this.setData({
      starIndex:event.detail.value
    })
  },
  onSubmit(){
    let descript = ''
    for(const k of this.data.modelList){
      descript += (k+1)+'.'+this.data.award.eduStarVos[this.data.starIndex].starModels[k].description
    }
    descript += '备注：' + this.data.remark;
    if(''==descript){
      wx.showToast({
        title: '请选择授星事由',
        icon: 'error',
        duration: 1000
      })
      return;
    }
    if(this.data.students.length == 0){
      wx.showToast({
        title: '请选择授予的学生',
        icon: 'error',
        duration: 1000
      })
      this.openStudentShow()
      return;
    }
    if(this.data.students.length > this.data.award.eduStarVos[this.data.starIndex].qty){
      wx.showToast({
        title: '星星不足',
        icon: 'error',
        duration: 1000
      })
      return;
    }
    let data ={
      teacherid:this.data.award.eduTeacherCourseClassVo.userid,
      courseid:this.data.award.eduTeacherCourseClassVo.courseid,
      departid:this.data.award.eduTeacherCourseClassVo.departid,
      studentid:this.data.students[0].userid,
      starid:this.data.award.eduStarVos[this.data.starIndex].starid,
      img1:this.data.imgList[0],
      descript:descript
    }
    let _this = this;
    let arr = [...this.data.students]
    arr.splice(0,1)
    app.api.saveAward(data).then(res => {
      if(res.code == 200){
        _this.setData({
          students:arr
        },()=>{
          if(0 == arr.length){
            this.get()
            wx.showModal({
              title: '提示',
              content: '保存成功!',
              showCancel:false,
              success(res) {
              }
            })
          }else{
            this.onSubmit()
          }
        })
      }
    })
  },
  openStudentShow(){
    const studentVos = [...this.data.award.eduStudentVos]
    studentVos.forEach(item=>{
      item.checked = this.data.students.some(ent=>{
        return item.userid === ent.userid
      })
    })
    const vo = {...this.data.award,'eduStudentVos':studentVos}
    console.log(vo)
    this.setData({
      studentShow:true,
      award:vo
    },()=>{
      this.filterEduStudentVos('')
    })
  },
  setSerchVal(e){
    this.setData({
      searchValue : e.detail.value
    })
    this.filterEduStudentVos(e.detail.value)
  },
  filterEduStudentVos(val){
    let list = []
    this.data.award.eduStudentVos.map(item=>{
      if(item.name.indexOf(val) >= 0){
        list.push(item)
      }
    })
    if(val.length>0){
      this.setData({
        list4Serach:list
      })
    }else{
      this.setData({
        list4Serach:this.data.award.eduStudentVos
      })
    }
  },
  oepnCanmaraShow(){
    this.setData({
      canmaraShow:true
    })
  },
  onPaichao(e){
    const ctx = wx.createCameraContext()
      ctx.takePhoto({
        quality: 'high',
        success: (res) => {
          const houzui = res.tempImagePath.slice(res.tempImagePath.indexOf('.')+1)
          let base64img = wx.getFileSystemManager().readFileSync(res.tempImagePath, "base64");
          base64img = 'data:image/'+houzui+';base64,'+base64img
          let arr = []
          arr.push(base64img)
          this.setData({
            imgList: arr,
            canmaraShow:false
          })
        }
      })
    },
  hideStudentModal(){
    this.setData({
      studentShow:false
    })
  },
  onTupianku(){
    let that = this;
    wx.chooseMedia({
      count: 1,
      mediaType:['image'],
      sizeType: ["compressed"],
      sourceType: ["album", "camera"],
      success: function (res) {
      const houzui = res.tempFiles[0].tempFilePath.slice(res.tempFiles[0].tempFilePath.indexOf('.')+1)
      let base64img = wx.getFileSystemManager().readFileSync(res.tempFiles[0].tempFilePath, "base64");
      base64img = 'data:image/'+houzui+';base64,'+base64img
          let arr = []
          arr.push(base64img)
          that.setData({
            imgList: arr,
            canmaraShow:false
          })
      },
  })
  },
  DelImg(e){
    this.setData({
      imgList:[]
    })
  },
  closeCanmaraShow(){
    this.setData({
      canmaraShow:false
    })
  },
  delStudent(e){
    let data = [...this.data.students]
    data.splice(e.currentTarget.dataset.index,1)
    this.setData({
      studentShow:false,
      students:data
    })
  },
  selStudent(e){
    addStudent(e.currentTarget.dataset.index)
  },
  addStudent(index){
    const stu = this.data.award.eduStudentVos[index]
    let data = [...this.data.students]
    if(data.some(item=>{
      return stu.userid === item.userid
    })){
      //提示
    }else{
      data.push(stu)
    }
    this.setData({
      students:data
    })
  },
  radioChange(e){
    this.setData({
      starIndex:e.detail.value
    })
  },
  cardSwiper(e){
    console.log(e.detail.current)
    this.setData({
      starIndex:e.detail.current
    })
  },
  checkboxChange(e){
    this.setData({
      modelList:e.detail.value
    })
  },
  inputArea(e){
    this.setData({
      remark:e.detail.value
    })
  },
  transformBase(res) {
    let that = this;
    var FSM = wx.getFileSystemManager();
    //循环将得到的图片转换为Base64
    for (let r in res.tempFilePaths) {
      // console.log(res.tempFilePaths[r])
      FSM.readFile({
        filePath: res.tempFilePaths[r],
        encoding: "base64",
        success: function(data) {
          let Working = data.data;
          that.getBase64ImageUrl(Working)
        }
      });
    }
  },
  checkboxChangeStudents(e){
    this.setData({
      students:[]
    })
    e.detail.value.forEach(item=>this.addStudent(item))
  },

})